package com.junjie.checkin.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.junjie.checkin.response.ResultStatus;
import com.junjie.checkin.response.Result;
import com.junjie.checkin.security.exception.TokenInvalidException;
import com.junjie.checkin.security.exception.TokenMissingException;
import com.junjie.checkin.security.service.AuthDetails;
import com.junjie.checkin.security.service.JwtService;
import com.junjie.checkin.security.service.impl.JwtServiceImpl;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * @author 洪浚杰
 * @description jwt过滤器
 * @date 2025/6/9 16:09
 */
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
    @Autowired
    private JwtServiceImpl jwtService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Value("${jwt.exclude-paths}")
    private List<String >excludePaths;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // cors预检跳过
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }
        // 检查是否为跳过路径
        if (isExcludePaths(request)){
            filterChain.doFilter(request,response);
            return;
        }
        // token校验
        try {
            String token = request.getHeader("Authorization");
            // 如果报错,抛出token缺失异常
            if (token == null || token.isEmpty()){
                throw  new TokenMissingException();
            }
            // 解析token
            AuthDetails userDetails = jwtService.analyzeToken(token);
            // 封装到Authentication对象中
            Authentication authentication= new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
            // 将认证信息放入context中
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 完成认证后放行
            filterChain.doFilter(request,response);

        }catch (TokenMissingException e){  // 令牌缺失
            responseMessage(response,HttpServletResponse.SC_UNAUTHORIZED,Result.getResult(ResultStatus.TOKEN_MISSING));
        }catch (TokenInvalidException e){  // 令牌失效
            responseMessage(response,HttpServletResponse.SC_UNAUTHORIZED,Result.getResult(ResultStatus.TOKEN_INVALID));
        }catch (ExpiredJwtException e){    // 令牌过期
            responseMessage(response,HttpServletResponse.SC_UNAUTHORIZED,Result.getResult(ResultStatus.TOKEN_EXPIRED));
        }catch (MalformedJwtException | UnsupportedJwtException | SignatureException e){  //令牌校验错误
            responseMessage(response,HttpServletResponse.SC_BAD_REQUEST,Result.getResult(ResultStatus.TOKEN_VERIFY_ERROR));
        }catch (Exception e){  // 其他错误
            System.out.println(e.getMessage());
            responseMessage(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR,Result.getResult(ResultStatus.SERVER_ERROR));
        }
    }

    /**
     * 判断是否为jwt排除的路径
     * @param request http请求对象
     * @return 是否为排除路径
     */
    private boolean isExcludePaths(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        for (String path: excludePaths){
            if (path.equals(requestURI)){
                return true;
            }
        }
        return false;
    }

    private void responseMessage(HttpServletResponse response, int status, Result responseResult) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(status);
        response.getOutputStream().write( new ObjectMapper().writeValueAsBytes(responseResult));
    };

}
